<template>
  <view class="login-container">
    <!-- 顶部Logo -->
    <view class="logo-section">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="welcome-text">欢迎登录</text>
    </view>
    
    <!-- 登录表单 -->
    <view class="form-section">
      <view class="input-group">
        <uni-icons type="phone" size="20" color="#999" class="input-icon"></uni-icons>
        <input 
          type="number" 
          v-model="phone" 
          placeholder="请输入手机号" 
          maxlength="11"
          class="input-item"
          @input="formatPhone"
          placeholder-class="placeholder-style"
        />
      </view>
      
      <view class="input-group password-input">
        <uni-icons type="locked" size="20" color="#999" class="input-icon"></uni-icons>
        <input 
          :type="showPassword ? 'text' : 'password'" 
          v-model="password" 
          placeholder="请输入密码" 
          class="input-item"
          placeholder-class="placeholder-style"
        />
        <view class="eye-icon" @click="showPassword = !showPassword">
           <uni-icons :type="showPassword ? 'eye' : 'eye-slash'" size="24" color="#999"></uni-icons> 
        </view>
      </view>
      
      <button class="login-btn" :disabled="isLoading" @click="handleLogin" hover-class="btn-hover">
        {{ isLoading ? '登录中...' : '登 录' }}
      </button>
      
      <view class="action-links">
        <text class="register-link" @click="goToRegister">立即注册</text>
        <text class="forgot-link" @click="goToForgotPassword">忘记密码?</text>
      </view>
      
      <!-- 错误提示 -->
      <view v-if="errorMessage" class="error-message">
        <uni-icons type="info" size="18" color="#ff4d4f"></uni-icons>
        <text class="error-text">{{ errorMessage }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      phone: '',
      password: '',
      showPassword: false,
      isLoading: false,
      errorMessage: ''
    }
  },
  methods: {
    // 格式化手机号输入
    formatPhone() {
      this.phone = this.phone.replace(/\D/g, '').slice(0, 11);
    },
    
    // 验证手机号格式
    validatePhone() {
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!this.phone) {
        this.errorMessage = '请输入手机号';
        return false;
      }
      if (!phoneReg.test(this.phone)) {
        this.errorMessage = '手机号格式不正确';
        return false;
      }
      this.errorMessage = '';
      return true;
    },
    
    // 验证密码
    validatePassword() {
      if (!this.password) {
        this.errorMessage = '请输入密码';
        return false;
      }
      if (this.password.length < 6) {
        this.errorMessage = '密码错误';
        return false;
      }
      this.errorMessage = '';
      return true;
    },
    
    // 处理登录
    async handleLogin() {
      if (this.isLoading) return;
      
      if (!this.validatePhone() || !this.validatePassword()) {
        return;
      }

      this.isLoading = true;
      this.errorMessage = '';
      
      try {
        // 调用登录接口
        const loginRes = await this.loginRequest();
        
        if (loginRes.success) {
          // 保存用户信息到本地存储
          uni.setStorageSync('userInfo', JSON.stringify(loginRes.user));
          uni.setStorageSync('token', loginRes.token);
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          });
          
          // 登录成功后跳转到首页
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/homepage/index'
            });
          }, 1500);
        } else {
          this.errorMessage = loginRes.message || '登录失败';
        }
      } catch (error) {
        console.error('登录出错:', error);
        this.errorMessage = error.message || '网络错误，请稍后再试';
      } finally {
        this.isLoading = false;
      }
    },
    
    // 登录请求
    loginRequest() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'http://localhost:3000/users',
          method: 'GET',
          success: (res) => {
            if (res.statusCode === 200) {
              // 处理不同格式的响应数据
              let users = [];
              if (Array.isArray(res.data)) {
                users = res.data;
              } else if (res.data && typeof res.data === 'object') {
                users = Object.values(res.data);
              } else {
                reject(new Error('无效的用户数据格式'));
                return;
              }
              
              // 查找匹配的用户
              const user = users.find(u => u.phone === this.phone && u.password === this.password);
              
              if (user) {
                resolve({
                  success: true,
                  user: {
                    _id: user.id,
                    username: user.username,
                    phone: user.phone
                  },
                  token: '模拟token_' + Date.now() // 模拟token
                });
              } else {
                resolve({
                  success: false,
                  message: '手机号或密码错误'
                });
              }
            } else {
              reject(new Error('服务器响应异常'));
            }
          },
          fail: (err) => {
            reject(new Error('网络连接失败'));
          }
        });
      });
    },
    
    // 跳转到注册页面
    goToRegister() {
      uni.navigateTo({
        url: '/pages/login/register'
      });
    },
    
    // 跳转到忘记密码页面
    goToForgotPassword() {
      uni.navigateTo({
        url: '/pages/login/forgot'
      });
    }
  }
}
</script>

<style lang="scss">
.login-container {
  min-height: 100vh;
  background: linear-gradient(to bottom, #f5f7fa, #e4e8eb);
  padding: 60rpx 50rpx;
  display: flex;
  flex-direction: column;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0 80rpx;
  
  .logo {
    width: 180rpx;
    height: 180rpx;
    border-radius: 50%;
    box-shadow: 0 10rpx 30rpx rgba(0, 134, 255, 0.2);
  }
  
  .welcome-text {
    margin-top: 40rpx;
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    letter-spacing: 2rpx;
  }
}

.form-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .input-group {
    background-color: #fff;
    border-radius: 50rpx;
    margin-bottom: 40rpx;
    padding: 0 30rpx;
    height: 100rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);
    
    .input-icon {
      margin-right: 20rpx;
    }
    
    .input-item {
      flex: 1;
      height: 100%;
      font-size: 32rpx;
      color: #333;
      /* 去除默认的黑色边框 */
      border: none;
      outline: none;
      /* 去除iOS下的内阴影 */
      -webkit-appearance: none;
    }
    
    &.password-input {
      .input-item {
        padding-right: 20rpx;
      }
      
      .eye-icon {
        padding: 10rpx;
      }
    }
  }
  
  .placeholder-style {
    color: #ccc;
    font-size: 30rpx;
  }
  
  .login-btn {
    background: linear-gradient(to right, #0081ff, #00acff);
    color: #fff;
    height: 100rpx;
    line-height: 100rpx;
    border-radius: 50rpx;
    font-size: 36rpx;
    margin-top: 70rpx;
    letter-spacing: 10rpx;
    box-shadow: 0 10rpx 20rpx rgba(0, 134, 255, 0.3);
    
    &[disabled] {
      background: #c0c0c0;
      opacity: 0.7;
    }
  }
  
  .btn-hover {
    opacity: 0.9;
    transform: translateY(2rpx);
  }
  
  .action-links {
    display: flex;
    justify-content: space-between;
    margin-top: 40rpx;
    padding: 0 20rpx;
    
    .register-link, .forgot-link {
      font-size: 28rpx;
      color: #666;
      
      &:active {
        color: #0086ff;
      }
    }
  }
  
  .error-message {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30rpx;
    padding: 20rpx;
    background-color: #fff2f0;
    border-radius: 10rpx;
    
    .error-text {
      margin-left: 10rpx;
      color: #ff4d4f;
      font-size: 26rpx;
    }
  }
  
  .third-party-login {
    margin-top: 100rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .divider {
      color: #999;
      font-size: 26rpx;
      position: relative;
      padding: 0 30rpx;
      
      &::before, &::after {
        content: '';
        position: absolute;
        top: 50%;
        width: 100rpx;
        height: 1rpx;
        background-color: #eee;
      }
      
      &::before {
        left: -100rpx;
      }
      
      &::after {
        right: -100rpx;
      }
    }
    
    .icons {
      display: flex;
      justify-content: center;
      margin-top: 40rpx;
      
      .icon-item {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        background-color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 30rpx;
        box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
        
        &:active {
          transform: scale(0.95);
        }
      }
    }
  }
}
</style>